import React, { useState, useEffect, useCallback } from 'react';
import { Table, message, Card, Button, Space, Popconfirm, Modal, Form, Input } from 'antd';
import type { ColumnsType, TablePaginationConfig } from 'antd/es/table';
import { LoadingOutlined, EditOutlined } from '@ant-design/icons';
import axios from 'axios';
import '../../css/clubs/clubList.css';

interface Club {
  id: number;
  name: string;
  description: string;
  type: string;
  president: string;
  created_at: string;
}

interface ApiResponse<T> {
  success: boolean;
  data: T;
  message?: string;
}

const ClubList: React.FC = () => {
  const [clubs, setClubs] = useState<Club[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [deleteLoading, setDeleteLoading] = useState<boolean>(false);
  const [pagination, setPagination] = useState<TablePaginationConfig>({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [editModalVisible, setEditModalVisible] = useState<boolean>(false);
const [editingClub, setEditingClub] = useState<Club | null>(null);
const [form] = Form.useForm();

  const fetchClubs = useCallback(async () => {
    setLoading(true);
    try {
      const response = await axios.get<ApiResponse<Club[]>>('http://localhost:5000/api/allClubs');
      if (response.data.success) {
        setClubs(response.data.data);
        setPagination(prev => ({
          ...prev,
          total: response.data.data.length,
        }));
      } else {
        message.error('获取社团列表失败');
      }
    } catch (error) {
      console.error('获取社团列表失败:', error);
      message.error('获取社团列表失败');
    } finally {
      setLoading(false);
    }
  }, []);


  
  const handleDelete = useCallback(async (club: Club) => {
    setDeleteLoading(true);
    try {
      const response = await axios.delete<ApiResponse<null>>(
        `http://localhost:5000/api/deleteClubs/${club.id}`
      );
      if (response.data.success) {
        message.success('社团删除成功');
        fetchClubs();
      } else {
        message.error(response.data.message || '删除社团失败');
      }
    } catch (error) {
      console.error('删除社团失败:', error);
      message.error('删除社团失败');
    } finally {
      setDeleteLoading(false);
    }
  }, [fetchClubs]);

  const handleEdit = useCallback((club: Club) => {
    setEditingClub(club);
    form.setFieldsValue({
      name: club.name,
      description: club.description,
      type: club.type,
      president: club.president
    });
    setEditModalVisible(true);
  }, [form]);

  // 添加提交修改函数
  const handleEditSubmit = useCallback(async () => {
    try {
      const values = await form.validateFields();
      const response = await axios.put<ApiResponse<Club>>(
        `http://localhost:5000/api/updateClub/${editingClub?.id}`,
        values
      );

      if (response.data.success) {
        message.success('社团信息更新成功');
        setEditModalVisible(false);
        fetchClubs();
      } else {
        message.error(response.data.message || '更新失败');
      }
    } catch (error) {
      console.error('更新社团信息失败:', error);
      message.error('更新失败，请稍后重试');
    }
  }, [editingClub, form, fetchClubs]);

  const handleTableChange = useCallback((newPagination: TablePaginationConfig) => {
    setPagination(newPagination);
  }, []);

  const columns: ColumnsType<Club> = [
    {
      title: '社团ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
      align: 'center',
      sorter: (a, b) => a.id - b.id,
    },
    {
      title: '社团名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string) => (
        <Button type="link" style={{ padding: 0, height: 'auto' }}>
          {text}
        </Button>
      ),
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      ellipsis: true,
    },
    {
      title: '社团描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '负责人',
      dataIndex: 'president',
      key: 'president',
      width: 120,
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 150,
      render: (date: string) => new Date(date).toLocaleDateString(),
      sorter: (a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime(),
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_, record) => (
        <Space size="middle">
         <Button 
  type="link" 
  size="small"
  icon={<EditOutlined />}
  onClick={() => handleEdit(record)}
>
  编辑
</Button>
          <Popconfirm
            title={`确定要移除社团 "${record.name}" 吗？`}
            okText="删除"
            okType="danger"
            cancelText="取消"
            onConfirm={() => handleDelete(record)}
          >
            <Button 
              type="link" 
              danger 
              size="small"
              loading={deleteLoading}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  useEffect(() => {
    fetchClubs();
  }, [fetchClubs]);

  return (
    <>
    <Card 
      title="社团列表" 
      bordered={false}
      extra={
        <Button type="primary" onClick={fetchClubs} loading={loading}>
          刷新
        </Button>
      }
    >
      <Table<Club>
        columns={columns}
        dataSource={clubs}
        rowKey="id"
        loading={{
          spinning: loading,
          indicator: <LoadingOutlined style={{ fontSize: 24 }} spin />,
        }}
        pagination={{
          ...pagination,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: total => `共 ${total} 条`,
        }}
        onChange={handleTableChange}
        bordered
        scroll={{ x: 'max-content' }}
      />
    </Card>

      {/* 添加编辑模态框 */}
      <Modal
        title="修改社团信息"
        open={editModalVisible}
        onOk={handleEditSubmit}
        onCancel={() => setEditModalVisible(false)}
        okText="保存"
        cancelText="取消"
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            name="name"
            label="社团名称"
            rules={[{ required: true, message: '请输入社团名称' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="type"
            label="社团类型"
            rules={[{ required: true, message: '请输入社团类型' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="description"
            label="社团描述"
          >
            <Input.TextArea rows={4} />
          </Form.Item>

          <Form.Item
            name="president"
            label="负责人"
            rules={[{ required: true, message: '请输入负责人姓名' }]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default ClubList;
